import requests
import hashlib
import time
import base64

from operation_ocr.confing import ConfingOcr

confing_data = ConfingOcr()


# 生成token
def calculate_md5(text):
    md5_hash = hashlib.md5()
    md5_hash.update(text.encode('utf-8'))
    md5_digest = md5_hash.hexdigest()

    return md5_digest


def get_image_size(image_path, extract_level=0):
    """
        请求参数：app_key+timestamp+token+image_data/image_file
    注：token生成方式（md5($appkey+$timestamp+$appSecret)
    token=md5("c5ed72329fece2fe0010a437505b01cb+1522374165+5c9597f3c8245907ea71a89d9d39d08e")
    =7007bd1257dce8d47489166a7c77a926）
    :return:
    """

    text = f'{confing_data.APP_KEY}+{int(time.time())}+{confing_data.APP_SECRET}'
    token = calculate_md5(text)
    url = confing_data.GET_URL
    # 发送文件
    with open(image_path, 'rb') as f:
        base64_data = base64.b64encode(f.read()).decode('utf-8')

    data = {
        'app_key': confing_data.APP_KEY,
        'timestamp': int(time.time()),
        'token': token,
        'image_data': base64_data,
        'extract_level': extract_level
    }

    response = requests.post(url, data=data)

    # 处理返回值
    if response.status_code == 200:
        return {'status': True, 'data': response.json()}
    else:
        return {'status': False, 'msg': f'上传文件失败，HTTP错误码:{response.status_code}'}


if __name__ == '__main__':
    # get_image_size(r'C:\Users\DuFei\Pictures\Saved Pictures\a4e9d215145b7612402081e426d6068.png')
    req = get_image_size(r'C:\Users\DuFei\Pictures\Saved Pictures\8b59bb061865f1778d5b71edbf937ad.png')
    if req:
        print(req['data']['response'])
    else:
        print(req)

